<template>
  <PageWrapper :contentFullHeight="true">
    <Row :gutter="24">
      <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
        <Tabs v-model:activeKey="activeKey" style="background-color: white">
          <TabPane key="1" :tab="t('routes.demo.documentWorkPlace.directory')">
            <div class="tree-container">
              <BasicTree
                ref="treeRef"
                :treeData="documentData"
                :toolbar="true"
                :search="true"
                @select="selectDoc"
                :beforeRightClick="rightClick"
                v-model:selectedKeys="selectedKeys"
                v-model:expandedKeys="expandedKeys"
              />
            </div>
          </TabPane>
        </Tabs>
      </Col>
      <Col :xs="24" :sm="24" :md="24" :lg="20" :xl="20" style="background-color: white">
        <Row>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <BasicTable
              @register="registerTable"
              :searchInfo="searchInfo"
              :rowSelection="{
                type: 'checkbox',
                selectedRowKeys: checkedKeys,
                onChange: onSelectChange,
              }"
            >
              <!-- 表格顶部左侧区域 -->
              <template #tableTitle>
                <Alert type="info" show-icon>
                  <template #message>
                    <template v-if="checkedKeys.length > 0">
                      <span
                        >{{ t('common.selected') }}
                        <a @click="getBatchData">{{ checkedKeys.length }}</a>
                        {{ t('common.records') }}</span
                      >
                      <a-button type="link" @click="checkedKeys = []" size="small">{{
                        t('common.clear')
                      }}</a-button>
                    </template>
                    <template v-else>
                      <span>{{ t('common.noSelected') }}</span>
                    </template>
                  </template>
                </Alert>
              </template>
              <!-- 右侧 -->
              <template #toolbar>
                <a-button
                  v-auth="['documentManager:workPlace:create']"
                  type="primary"
                  @click="handleCreateDoc"
                >
                  {{ t('common.create') }}
                </a-button>
                <!-- 发布 -->
                <a-button
                  color="error"
                  @click="handleDocPublish(null)"
                  :disabled="checkedKeys.length == 0"
                >
                  {{ t('routes.demo.documentManager.operationButton.publish') }}
                </a-button>
                <!-- 共享 -->
                <a-button
                  type="primary"
                  @click="handleShare(null)"
                  :disabled="checkedKeys.length == 0"
                >
                  {{ t('routes.demo.documentManager.operationButton.share') }}
                </a-button>
              </template>
              <!-- 代号 -->
              <template #name="{ text: name, record }">
                <Row>
                  <Col :span="22" class="text-ellipsis">
                    <Tooltip :title="name">
                      <a @click="getCurrentRecord(record)">{{ name }}</a>
                    </Tooltip>
                  </Col>
                  <Col :span="2"
                    ><Icon
                      icon="ion:ios-copy-outline"
                      color="#7a7374"
                      @click="handleCopy(name)"
                      style="cursor: pointer"
                  /></Col>
                </Row>
              </template>
              <!-- 创建时间 -->
              <template #creattime="{ text: creattime }">
                <span>
                  {{ proxy.$filters.filterTime(creattime) }}
                </span>
              </template>
              <!-- 文档状态 -->
              <template #state="{ text: state }">
                <span>
                  <Tag :color="state === '8' ? 'green' : state === '1' ? 'red' : 'blue'">
                    {{ proxy.$filters.filterDocumentStatus(state) }}
                  </Tag>
                </span>
              </template>
              <!-- 是否为关联文件 -->
              <template #isshortcut="{ text: isshortcut }">
                <span>
                  <Tag :color="isshortcut === '1' ? 'green' : isshortcut === '0' ? 'red' : 'blue'">
                    {{ proxy.$filters.filterIsRelated(isshortcut) }}
                  </Tag>
                </span>
              </template>
              <!-- 是否所属零件 -->
              <template #isPartAttachment="{ text: isPartAttachment }">
                <span>
                  {{ isPartAttachment === '1' ? t('common.yes') : t('common.no') }}
                </span>
              </template>
              <!-- 零件信息 -->
              <template #partInfo="{ text: partInfo }">
                <span>
                  <Tooltip :title="partInfoTitle(partInfo)">
                    {{
                      partInfo != null
                        ? `零件代号：${partInfo.partThitObjectId}-零件名称：${
                            partInfo.partName
                          }-零件类型：${
                            partInfo.partType
                          }-零件状态：${proxy.$filters.filterPartStatus(
                            partInfo.partStatus,
                          )}-零件版本：${partInfo.partVersion}`
                        : '无'
                    }}
                  </Tooltip>
                </span>
              </template>
              <!-- 操作 -->
              <template #action="{ record }">
                <TableAction
                  :actions="[
                    {
                      icon: 'ion:ios-download-outline',
                      tooltip: t('common.checkIn'),
                      popConfirm: {
                        title: t('common.directCheckIn'),
                        placement: 'top',
                        confirm: handleDirectCheckIn.bind(null, record),
                        cancel: handleCheckIn.bind(null, record),
                        okText: t('common.yes'),
                        cancelText: t('common.no'),
                      },
                      ifShow:
                        record.state === '1' &&
                        record.prdpower?.some((item) => item.permissionNames == '检入对象'),
                    },
                    {
                      icon: 'ion:ios-upload-outline',
                      tooltip: t('common.checkOut'),
                      popConfirm: {
                        title: t('common.directCheckOut'),
                        placement: 'top',
                        confirm: handleDirectCheckOut.bind(null, record),
                        cancel: handleCheckOut.bind(null, record),
                        okText: t('common.yes'),
                        cancelText: t('common.no'),
                      },
                      ifShow:
                        record.state === '8' &&
                        record.prdpower?.some((item) => item.permissionNames == '检出对象'),
                    },
                    {
                      icon: 'ion:ios-redo-outline',
                      tooltip: t('common.undo'),
                      popConfirm: {
                        title: t('common.confirmUndo'),
                        placement: 'top',
                        confirm: handleCancel.bind(null, record),
                      },
                      ifShow:
                        record.state === '1' &&
                        record.prdpower?.some((item) => item.permissionNames == '撤销对象'),
                    },
                    {
                      icon: 'ion:trash-outline',
                      tooltip: t('common.delete'),
                      color: 'error',
                      popConfirm: {
                        title: t('common.confirmDelete'),
                        placement: 'top',
                        confirm: handleDelete.bind(null, record),
                      },
                      ifShow:
                        record.state === '8' &&
                        record.prdpower?.some((item) => item.permissionNames == '删除对象'),
                    },
                    {
                      icon: 'icon-park-outline:preview-open',
                      tooltip: t('routes.demo.documentManager.operationButton.browse'),
                      onClick: handleBrowse.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '浏览对象'),
                    },
                    // 修改
                    {
                      icon: 'material-symbols:edit-square-outline',
                      tooltip: t('common.edit'),
                      onClick: handleEdit.bind(null, record),
                    },
                  ]"
                  :dropDownActions="[
                    {
                      label: t('routes.demo.documentManager.operationButton.view'),
                      onClick: handleDocDetail.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '查看对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.publish'),
                      onClick: handleDocPublish.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '发布对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.share'),
                      onClick: handleShare.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '共享对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.borrow'),
                      onClick: handleBorrow.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '借阅对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.abolish'),
                      onClick: handleAbolish.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '废止对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.compareBrowse'),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '比较浏览对象',
                      ),
                      onClick: handleCompareBrowse.bind(null, record),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.versionCompare'),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '版本比较对象',
                      ),
                      onClick: handleVersionCompare.bind(null, record),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.downloadDoc'),
                      onClick: handleDownload.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '下载对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.printDocument'),
                      onClick: handlePrint.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '打印对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.convert'),
                      // ifShow: record.prdpower?.some((item) => item.permissionNames == '转换对象'),
                      ifShow: false, // 暂时隐藏
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.usage'),
                      // onClick: handleUsage.bind(null, record),
                      // ifShow: record.prdpower?.some((item) => item.permissionNames == '使用情况对象'),
                      ifShow: false, // 暂时隐藏
                    },
                    {
                      label: t(
                        'routes.demo.documentManager.operationButton.relatedProcessInstance',
                      ),
                      onClick: handleFlowDetail.bind(null, record),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '相关流程示例对象',
                      ),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.associatedObject'),
                      onClick: handleAssociated.bind(null, record),
                      ifShow: record.prdpower?.some((item) => item.permissionNames == '关联对象'),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.reverseAssociated'),
                      onClick: handleReverseAssociated.bind(null, record),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '反向关联对象',
                      ),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.newProcess'),
                      onClick: handleCreateFlow.bind(null, record),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '新建流程对象',
                      ),
                    },
                    {
                      label: t('routes.demo.documentManager.operationButton.workAssign'),
                      onClick: handleAssign.bind(null, record),
                      ifShow: record.prdpower?.some(
                        (item) => item.permissionNames == '工作指派对象',
                      ),
                    },
                  ]"
                />
              </template>
            </BasicTable>
          </Col>
        </Row>
        <Divider />
        <Row>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <Tabs v-model:activeKey="docDetailActiveKey">
              <!-- <TabPane key="1" tab="属性">
                <Row :gutter="12">
                  <Col :xs="4" :sm="4" :md="4" :lg="4" :xl="4" />
                  <Col :xs="4" :sm="4" :md="4" :lg="4" :xl="4"> 文件名称：{{ fileName }} </Col>
                  <Col :xs="4" :sm="4" :md="4" :lg="4" :xl="4"> 版本：{{ version }} </Col>
                  <Col :xs="6" :sm="6" :md="6" :lg="6" :xl="6"> 类型：{{ type }} </Col>
                  <Col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
                    创建时间：{{ proxy.$filters.filterTime(createTime) }}
                  </Col>
                </Row>
              </TabPane> -->
              <!-- <TabPane key="2" :tab="t('routes.demo.documentManager.DocPreview')">
                <iframe
                  v-show="iframeLoading"
                  ref="ifameName"
                  :src="previewSrc"
                  frameborder="10"
                  style="width: 95%; height: 300px"
                  :onload="onload"
                ></iframe>
                <Empty v-show="!iframeLoading" :description="description" />
              </TabPane> -->
              <TabPane key="3" :tab="t('routes.demo.documentManager.DocVersionShow')">
                <BasicTable
                  @register="registerVersion"
                  :dataSource="versionList"
                  :rowSelection="{
                    type: 'checkbox',
                    selectedRowKeys: checkedVerKeys,
                    onChange: onSelectVerChange,
                  }"
                >
                  <!-- 右侧 -->
                  <template #toolbar>
                    <a-button
                      type="primary"
                      @click="CompareBrowse"
                      :disabled="checkedVerKeys.length != 2"
                    >
                      {{ t('routes.demo.documentManager.operationButton.compareBrowse') }}
                    </a-button>
                  </template>
                  <!-- 操作 -->
                  <template #action="{ record }">
                    <TableAction
                      :actions="[
                        {
                          icon: 'icon-park-outline:preview-open',
                          tooltip: t('routes.demo.documentManager.operationButton.browse'),
                          onClick: versionPreview.bind(null, record),
                          ifShow: record.prdpower?.some(
                            (item) => item.permissionNames == '浏览对象',
                          ),
                        },
                      ]"
                    />
                  </template>
                </BasicTable>
              </TabPane>
              <!-- <TabPane key="4" :tab="t('routes.demo.documentManager.DocChangeRecord')"> 4 </TabPane> -->
              <TabPane key="5" :tab="t('routes.demo.documentManager.DocRelatedDoc')">
                <BasicTable @register="registerAssociatedImage" :dataSource="associatedImageList" />
              </TabPane>
            </Tabs>
          </Col>
        </Row>
      </Col>
    </Row>
    <!-- 新建图档-选择图档类型 -->
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.documentWorkPlace.selectFileType')"
      @register="registerDireTypeModal"
      @ok="handleSubmit"
      @cancel="cancelDocType"
      :destroyOnClose="true"
      :minHeight="100"
      :width="400"
    >
      <Select
        allowClear
        style="width: 100%"
        :placeholder="t('routes.demo.documentWorkPlace.selectFileType')"
        v-model:value="fileType"
        @select="handleSelect"
      >
        <SelectOption
          v-for="(item, index) in documentTypeList"
          :value="item.fileTypeId"
          :key="index"
          >{{ item.fileTypeName }}</SelectOption
        >
      </Select>
    </BasicModal>
    <!-- 详情弹窗 -->
    <!-- 目录新增修改 -->
    <directoryModal @register="registerDireModal" @success="reloadGetDirectoryLevel" />
    <!-- 检入检出流程 -->
    <initiateFlowCopy @register="registerModalCopy" />
    <!-- 对象类绑定 -->
    <objBindModal @register="registerObjBindModal" />
    <!-- 关联，反关联弹窗 -->
    <assObjModal @register="registerAssociatedModal" @success="reload()" />
    <!-- 相关流程实例 -->
    <flowDetailModal @register="registerFlowDetailModal" />
    <!-- 文件导入弹窗 -->
    <importFileModal @register="registerFileImportModal" @success="reload()" />
    <!-- 借阅流程 -->
    <selectForm @register="registerBorrowModal" />
    <!-- 目录工作指派 -->
    <workAssignModal @register="registerDireWorkModal" />
    <!-- 文件工作指派 -->
    <DocWorkAssign @register="registerDocWorkModal" @success="reload()" />
    <!-- 新建图文档-文档类型弹窗 -->
    <CreateDocModal @register="registerDocumentTypeModal" @success="reload()" />
    <!-- 使用情况 -->
    <usage @register="registerUsageModal" />
    <!-- 提取导入 -->
    <extractImport @register="registerExtractImportModal" />
    <!-- Excel导入 -->
    <excelImport @register="registerExcelImportModal" />
    <!-- 新建流程 -->
    <CreateFlowModal @register="registerCreateFlowModal" />
    <!-- 目录权限设置 -->
    <permissionModal @register="registerPermissionModal" />
    <!-- 新建表单类型图文档 -->
    <formTypeModal @register="registerFormTypeModal" @success="reload()" />
    <!-- 发布 -->
    <createRelModal @register="registerRelModal" @cancelRel="cancelRelation" />
    <!-- 版本比较 -->
    <docVersionModel @register="registerDocVersionModal" />
    <!-- 比较浏览 -->
    <CompareViewModal @register="registerCompareViewModal" />
    <!-- 解绑归档 -->
    <unbindModal @register="registerUnbindModal" @success="reloadGetDirectoryLevel" />
    <!-- 批量操作弹窗 -->
    <batchModal @register="registerBatchModal" />
    <!-- onlyOffice预览 -->
    <onlyOffice @register="registerOnlyOfficeModal" />
    <!-- 关联零件 -->
    <partManagerModal @register="registerPartManagerModal" @success="assPartSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, nextTick, getCurrentInstance } from 'vue';
  import {
    Row,
    Col,
    Tabs,
    TabPane,
    Divider,
    Select,
    SelectOption,
    Empty,
    Tooltip,
    Tag,
    Alert,
    Modal,
  } from 'ant-design-vue';

  import dayjs from 'dayjs';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import throttle from 'lodash/throttle';
  import { Base64 } from 'js-base64';
  import { Icon } from '/@/components/Icon';
  import { useUserStore } from '/@/store/modules/user';
  import printJS from 'print-js';

  import {
    getDocumentColumns,
    getDocumentConfig,
    getPartVersionList,
    getAssociatedImageList,
  } from './tableData';
  import createRelModal from './releaseArea/createRelModal.vue';
  import objBindModal from './objBindModal.vue';
  import directoryModal from './directoryModal.vue';
  import assObjModal from './assObjModal.vue';
  import flowDetailModal from './flowDetailModal.vue';
  import importFileModal from './importFileModal.vue';
  import selectForm from '../formManager/selectForm.vue';
  import workAssignModal from './workAssignModal.vue';
  import DocWorkAssign from './DocWorkAssign.vue';
  import CreateDocModal from './CreateDocModal.vue';
  import usage from './usage.vue';
  import extractImport from './extractImport.vue';
  import excelImport from './excelImport.vue';
  import CreateFlowModal from '/@/views/components/createNewProcess.vue';
  import permissionModal from './components/permissionModal.vue';
  import formTypeModal from './components/formTypeModal.vue';
  import docVersionModel from './components/docVersionModel.vue';
  import CompareViewModal from './components/CompareViewModal.vue';
  import unbindModal from './unbindModal.vue';
  import batchModal from '/@/views/components/batchModal.vue';
  import initiateFlowCopy from '../workFlow/initiateFlowCopy.vue';
  import partManagerModal from '/@/views/demo/partManager/components/partManagerModal.vue';

  // 引入onlyoffice组件
  import onlyOffice from '/@/views/demo/documentManager/components/onlyOffice.vue';

  import {
    getDirectoryLevel,
    deletePrdFolder,
    getPrdFolder,
    addLibraryIndex,
    getPrdFileList,
    cancelFile,
    deleteFile,
    checkIn,
    checkOut,
    downloadFile,
    getPrdFileVersionList,
    downloadFolderList,
    getRelatedFileList,
    getWorkAssignList,
    getAllFileType,
    browseFile,
    PasteResourceTaskUse,
    ReversesActivatePower,
    JudgeAbolishedDocData,
    ExtractFileByAutoView,
    GetPreviewSettings,
    printFile,
    DownloadAllFilesAsBinary,
    ArchiveDirectory,
    SelectPrdForFiles,
    GetIsInWorkflow,
    ExtractManyFileByAutoView,
    addFolderBindingObject,
    DeleteFolderShortCut,
  } from '/@/api/demo/document';
  import { getBorrowBdDataJudge } from '/@/api/demo/knowledge';

  import { handleBrowseFile } from '/@/utils/demo/preview';

  const useCommonStore = useUserStore();
  // 定义默认值
  const { t } = useI18n();
  const { proxy }: any = getCurrentInstance();
  const { createMessage } = useMessage();
  const documentSuperId = ref<number>(0);
  const documentData = ref<any>([]);
  const activeKey = ref<string>('1');
  const docDetailActiveKey = ref<string>('3');
  const selectedDocKey = ref<string>('');
  const selectRowClass = ref<any>('');
  // 文件名称
  const fileName = ref<string>('');
  // 版本
  const version = ref<string>('');
  // 类型
  const type = ref<string>('');
  // 创建时间
  const createTime = ref<string>('');
  // 版本展示
  const versionList = ref<any>([]);
  // 相关图档
  const associatedImageList = ref<any>([]);
  // 图档类型
  const documentTypeList = ref<any>([]);
  const fileType = ref<string>(null);
  const isBdData = ref<any>({});
  const previewSrc = ref<string>('');
  const ifameName = ref(null);
  const iframeLoading = ref(false);
  const description = ref('暂无数据');
  // 复制目录id
  const copyDireId = ref<string>('');
  // 目录搜索条件
  const searchInfo = ref<any>({
    CurrentDirId: '',
  });
  const checkedKeys = ref<Array<string | number>>([]); // 选中的键
  const selectedRows = ref<any>([]); // 选中的行数据
  const treeRef = ref<any>(null);
  const selectedKeys = ref([]); // 选中节点
  const expandedKeys = ref([]); // 需要展开的节点
  const versionOid = ref<string>('');
  const checkedVerKeys = ref<Array<string | number>>([]); // 选中的键
  const selectedVerRows = ref<any>([]); // 选中的行数据

  const onload = () => {
    const iframe = ifameName.value;
    if (iframe !== null) {
      if (iframe && iframe.contentWindow) {
        iframeLoading.value = true;
      } else {
        iframe.addEventListener('load', () => {
          iframeLoading.value = true;
        });
      }
    }
  };

  // 接口请求
  getDirectoryLevel(documentSuperId.value).then((res) => {
    documentData.value = res;
  });
  const reloadGetDirectoryLevel = () => {
    getDirectoryLevel(documentSuperId.value).then((res) => {
      nextTick(() => {
        documentData.value = res;
      });
    });
  };

  // 新建图档
  const handleCreateDoc = () => {
    if (selectedDocKey.value === '') {
      createMessage.warning(t('routes.demo.partManagerSettings.directoryPlaceholder'));
    } else {
      let fid = Number(selectedDocKey.value);
      getAllFileType(fid).then((res) => {
        documentTypeList.value = res.filter((e) => e.isAttach !== '1');
      });
      openDireTypeModal(true);
    }
  };

  // 在线编辑
  const handleEdit = async (record: any) => {
    if (record.prdpower.some((item) => item.permissionNames == '编辑对象')) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.checkOutPerson !== useCommonStore.userInfo?.userId) {
        createMessage.error('只能执行检出人为自己的对象');
      } else if (record.state !== '1') {
        createMessage.error('仅可编辑检出的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        const configList = {
          oId: record.oId,
          version: record.version,
          userId: useCommonStore.userInfo.userId,
          mode: 'edit',
        };
        openPreviewModal(true, { configList });
      }
    } else {
      createMessage.error('没有权限编辑');
    }
  };

  const selectDoc = (selectedKeys) => {
    selectedDocKey.value = selectedKeys[0];
    searchInfo.value.CurrentDirId = selectedDocKey.value;
    reload();
  };

  // 递归函数
  const findTitleByKey = (node, targetKey) => {
    // 如果当前节点的 key 匹配，返回 title
    if (node.key === targetKey) {
      return node.title;
    }
    // 如果当前节点有子节点，则递归查找
    if (node.children && Array.isArray(node.children)) {
      for (const child of node.children) {
        const result = findTitleByKey(child, targetKey);
        if (result) return result; // 找到匹配项立即返回
      }
    }
    return null; // 未找到返回 null
  };

  const handleDeleteClick = (eventKey: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deletePrdFolder(eventKey);
          reloadGetDirectoryLevel();
          createMessage.success('删除成功');
        } catch (error) {
          createMessage.error('删除失败');
        }
      },
    });
  };

  const rightClick = async (node: any, event: any) => {
    const direSelectData = node.eventKey.split(' ');
    const userSelectData = useCommonStore.userInfo.userId;
    let result = await ReversesActivatePower(direSelectData, [userSelectData]);

    // 解决报错问题，确保 result 至少是一个空数组
    result = result || [];
    const arr = [
      {
        label: t('routes.direPermission.basicFunction'),
        children: [
          {
            label: t('routes.direPermission.createDataDirectory'),
            handler: () => {
              openDireModal(true, { treeKey: node.eventKey, isUpdate: false });
            },
            isShow:
              result.some((item) => item.permissionNames === '新建数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.modifyDataDirectory'),
            handler: () => {
              getPrdFolder(node.eventKey).then((res) => {
                openDireModal(true, { treeKey: node.eventKey, isUpdate: true, res });
              });
            },
            isShow:
              result.some((item) => item.permissionNames === '修改数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.deleteDataDirectory'),
            handler: () => handleDeleteClick(node.eventKey),
            isShow:
              result.some((item) => item.permissionNames === '删除数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.copyDataDirectory'),
            handler: () => {
              copyDireId.value = node.eventKey;
              if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard
                  .writeText(node.eventKey)
                  .then(() => {
                    createMessage.success(t('common.copySuccessText'));
                  })
                  .catch(() => {
                    handleCopyFallback(node.eventKey);
                  });
              } else {
                handleCopyFallback(node.eventKey);
              }
            },
            isShow:
              result.some((item) => item.permissionNames === '复制数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.pasteDataDirectory'),
            handler: () => {
              if (copyDireId.value !== '') {
                PasteResourceTaskUse(copyDireId.value, node.eventKey).then(() => {
                  reloadGetDirectoryLevel();
                  copyDireId.value = '';
                  createMessage.success(t('common.pasteSuccessText'));
                });
              } else {
                createMessage.warning(t('common.pasteWarningText'));
              }
            },
            isShow:
              result.some((item) => item.permissionNames === '粘贴数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.archiveDataDirectory'),
            isShow:
              result.some((item) => item.permissionNames === '归档数据目录') ||
              useCommonStore.userInfo.userId === 'sa',
            handler: () => {
              ArchiveDirectory(node.eventKey).then((res) => {
                if (res) {
                  createMessage.success('归档成功');
                }
              });
            },
          },
        ],
        isShow: true,
      },
      {
        label: t('routes.direPermission.KnowledgeBaseIndex'),
        handler: () => {
          addLibraryIndex(Number(node.eventKey)).then(() => {
            createMessage.success(t('common.addSuccessText'));
          });
        },
        isShow:
          result.some((item) => item.permissionNames === '知识库索引目录') ||
          useCommonStore.userInfo.userId === 'sa',
      },
      {
        label: t('routes.direPermission.WorkAssignment'),
        handler: () => {
          getWorkAssignList(node.eventKey, '1').then((res) => {
            openDireWorkModal(true, res);
          });
        },
        isShow:
          result.some((item) => item.permissionNames === '工作指派目录') ||
          useCommonStore.userInfo.userId === 'sa',
      },
      {
        label: t('routes.direPermission.DocumentList'),
        handler: () => {
          downloadFolderList(node.eventKey).then(() => {
            createMessage.success(t('common.exportSuccessText'));
          });
        },
        isShow:
          result.some((item) => item.permissionNames === '图档清单目录') ||
          useCommonStore.userInfo.userId === 'sa',
      },
      {
        label: t('routes.direPermission.DownloadDocument'),
        isShow:
          result.some((item) => item.permissionNames === '下载目录') ||
          useCommonStore.userInfo.userId === 'sa',
        handler: () => {
          const dicTitle = findTitleByKey({ children: documentData.value }, node.eventKey);
          DownloadAllFilesAsBinary(node.eventKey, dicTitle + '.zip').then(() => {
            createMessage.success(t('common.downLoadSuccess'));
          });
        },
      },
      {
        label: t('routes.direPermission.Import'),
        children: [
          {
            label: t('routes.direPermission.LocalFileImport'),
            handler: () => {
              let fid = Number(node.eventKey);
              getAllFileType(fid).then((res) => {
                const newData = res
                  .filter((e) => e.isAttach !== '1')
                  .map((item) => {
                    return {
                      label: item.fileTypeName,
                      value: item.fileTypeId,
                    };
                  });
                openFileImportModal(true, { treeKey: node.eventKey, docType: newData });
              });
            },
            isShow: true,
          },
          {
            label: t('routes.direPermission.ExtractImport'),
            handler: () => {
              openExtractImportModal(true, { treeKey: node.eventKey });
            },
            isShow: false,
          },
          {
            label: t('routes.direPermission.ExcelImport'),
            handler: () => {
              openExcelImportModal(true, { treeKey: node.eventKey });
            },
            isShow: false,
          },
          {
            label: t('routes.direPermission.DataImport'),
            isShow: false,
          },
        ],
        isShow: true,
      },
      {
        label: t('routes.direPermission.Export'),
        children: [
          {
            label: t('routes.direPermission.ExportByDirectory'),
            isShow:
              result.some((item) => item.permissionNames === '按目录导出') ||
              useCommonStore.userInfo.userId === 'sa',
            handler: () => {
              const dicTitle = findTitleByKey({ children: documentData.value }, node.eventKey);
              DownloadAllFilesAsBinary(node.eventKey, dicTitle + '.zip').then(() => {
                createMessage.success(t('common.downLoadSuccess'));
              });
            },
          },
          {
            label: t('routes.direPermission.ExportByDirectoryVersionSeparation'),
            // isShow:
            //   result.some((item) => item.permissionNames === '按目录版本分离导出') ||
            //   useCommonStore.userInfo.userId === 'sa',
            isShow: false,
          },
          {
            label: t('routes.direPermission.ExportByBom'),
            // isShow:
            //   result.some((item) => item.permissionNames === '按BOM导出') ||
            //   useCommonStore.userInfo.userId === 'sa',
            isShow: false,
          },
        ],
        isShow: true,
      },
      {
        label: t('routes.direPermission.Print'),
        children: [
          {
            label: t('routes.direPermission.PrintDrawing'),
            children: [
              {
                label: t('routes.direPermission.CADDrawing'),
                isShow:
                  result.some((item) => item.permissionNames === 'CAD图纸打印') ||
                  useCommonStore.userInfo.userId === 'sa',
              },
              {
                label: t('routes.direPermission.SLDDRW'),
                isShow:
                  result.some((item) => item.permissionNames === 'SLDDRW图纸打印') ||
                  useCommonStore.userInfo.userId === 'sa',
              },
            ],
            isShow: true,
          },
          {
            label: t('routes.direPermission.PrintByBom'),
            children: [
              {
                label: t('routes.direPermission.onlyCADDrawing'),
                isShow:
                  result.some((item) => item.permissionNames === 'BOM打印CAD') ||
                  useCommonStore.userInfo.userId === 'sa',
              },
              {
                label: t('routes.direPermission.onlySLDDRW'),
                isShow:
                  result.some((item) => item.permissionNames === 'BOM打印SLDDRW') ||
                  useCommonStore.userInfo.userId === 'sa',
              },
            ],
            isShow: true,
          },
        ],
        isShow: false,
      },
      {
        label: t('routes.direPermission.Convert'),
        children: [
          {
            label: t('routes.direPermission.SLDDRWToDWG'),
            isShow:
              result.some((item) => item.permissionNames === 'SLDDRW转DWG') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.SLDDRWToPDF'),
            isShow:
              result.some((item) => item.permissionNames === 'SLDDRW转PDF') ||
              useCommonStore.userInfo.userId === 'sa',
          },
        ],
        isShow: false,
      },
      {
        label: t('routes.direPermission.Setting'),
        children: [
          {
            label: t('routes.direPermission.permission'),
            handler: () => {
              openDirePermissionModal(true, { treeKey: node.eventKey });
            },
            isShow:
              result.some((item) => item.permissionNames === '设置权限') ||
              useCommonStore.userInfo.userId === 'sa',
          },
          {
            label: t('routes.direPermission.objectClassBinding'),
            handler: () => {
              openObjBindModal(true, { treeKey: node.eventKey, type: '图档' });
            },
            isShow:
              result.some((item) => item.permissionNames === '设置对象类绑定') ||
              useCommonStore.userInfo.userId === 'sa',
          },
        ],
        // isShow:
        //   result.some((item) => item.permissionNames === '设置') ||
        //   useCommonStore.userInfo.userId === 'sa',
      },
      {
        label: '归档解绑',
        handler: () => {
          openUnbindModal(true, { treeKey: node.eventKey, type: '解绑' });
        },
      },
    ];
    // 过滤掉 isShow 为 false 的数据
    const filteredData = filterData(arr);
    return filteredData;
  };
  // 过滤掉 isShow 为 false 的数据
  function filterData(data) {
    return data
      .filter((item) => item.isShow !== false) // 过滤掉 isShow 为 false 的项
      .map((item) => {
        // 如果存在 children，递归处理
        if (item.children) {
          return {
            ...item,
            children: filterData(item.children), // 递归过滤子项
          };
        }
        return item; // 如果没有 children，直接返回
      });
  }
  // 查看
  const handleDocDetail = (record: Recordable) => {
    // 如果record.dataType与64进行按位与操作的结果不为0
    if (record.dataType & 64) {
      openFormTypeModal(true, {
        fileType: fileType.value,
        selectedDirKey: selectedDocKey.value,
        oid: record.oId,
        typeName: record.type,
        version: record.version,
        type: '查看',
      });
    } else {
      // 图档
      openDirModal(true, {
        fileType: record.goodsclsid,
        selectedDirKey: selectedDocKey.value,
        isUpdate: true,
        record: record,
      });
    }
  };

  // 发布
  const handleDocPublish = async (record: Recordable | null) => {
    const recordsToHandle = record ? [record] : selectedRows.value;
    const type = record ? '单个' : '批量';

    // 校验流程状态
    const invalidItems = [];
    for (const item of recordsToHandle) {
      const isFlow = await GetIsInWorkflow(item.oId);
      if (!isFlow) {
        invalidItems.push(item);
      }
    }

    if (invalidItems.length > 0) {
      createMessage.error('所选文件中存在已在流程中的文件，请先结束流程');
      return;
    }

    // 打开发布模态框
    await openRelModal(true, {
      relList: recordsToHandle,
      relType: type,
      modalType: 'publish',
    });
  };

  const cancelRelation = () => {
    selectedRows.value = [];
    checkedKeys.value = [];
  };

  // 分享功能
  const handleShare = async (record: Recordable) => {
    const recordsToHandle = record ? [record] : selectedRows.value;
    const type = record ? '单个' : '批量';

    // 校验流程状态
    const invalidItems = [];
    for (const item of recordsToHandle) {
      const isFlow = await GetIsInWorkflow(item.oId);
      if (!isFlow) {
        invalidItems.push(item);
      }
    }

    if (invalidItems.length > 0) {
      createMessage.error('所选文件中存在已在流程中的文件，请先结束流程');
      return;
    }

    // 打开发布模态框
    await openRelModal(true, {
      relList: recordsToHandle,
      relType: type,
      modalType: 'share',
    });
  };

  //  直接检入
  const handleDirectCheckIn = async (record: Recordable) => {
    if (
      record.prdpower.some((item) => item.permissionNames == '直接检入对象') ||
      useCommonStore.userInfo.userId === 'sa'
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.checkOutPerson !== useCommonStore.userInfo?.userId) {
        createMessage.error('只能执行检出人为自己的对象');
      } else if (record.state !== '1') {
        createMessage.error('仅可检入检出的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        checkIn(record.id).then(() => {
          reload();
          createMessage.success(t('common.checkInSuccessText'));
        });
      }
    } else {
      createMessage.error('没有权限直接检入');
    }
  };

  // 按流程检入
  const handleCheckIn = async (record: Recordable) => {
    if (record.prdpower.some((item) => item.permissionNames == '检入对象')) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.checkOutPerson !== useCommonStore.userInfo?.userId) {
        createMessage.error('只能执行检出人为自己的对象');
      } else if (record.state !== '1') {
        createMessage.error('仅可检入检出的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        openModalCopy(true, {
          record: record,
          type: '检入流程',
          selectedFiles: '',
          projectid: '',
          projectName: '',
          taskName: '',
          formId: '',
          state: '图档',
          isUpdate: false,
        });
      }
    } else {
      createMessage.error('没有权限检入');
    }
  };

  // 直接检出
  const handleDirectCheckOut = async (record: Recordable) => {
    if (
      record.prdpower.some(
        (item) => item.permissionNames == '直接检出对象' || useCommonStore.userInfo.userId === 'sa',
      )
    ) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.state !== '8') {
        createMessage.error('仅可检出生效的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        checkOut(record.id).then(() => {
          createMessage.success(t('common.checkOutSuccessText'));
          reload();
        });
      }
    } else {
      createMessage.error('没有权限直接检出');
    }
  };

  // 按流程检出
  const handleCheckOut = async (record: Recordable) => {
    if (record.prdpower.some((item) => item.permissionNames == '检出对象')) {
      const isFlow = await GetIsInWorkflow(record.oId); // 统一获取流程状态
      if (record.state !== '8') {
        createMessage.error('仅可检出生效的对象');
      } else if (!isFlow) {
        createMessage.error('该文件已在流程中，请先结束流程');
      } else {
        openModalCopy(true, {
          record: record,
          type: '检出流程',
          selectedFiles: '',
          projectid: '',
          projectName: '',
          taskName: '',
          formId: '',
          state: '图档',
          isUpdate: false,
        });
      }
    } else {
      createMessage.error('没有权限检出');
    }
  };

  // 撤销
  const handleCancel = (record: Recordable) => {
    cancelFile(record.id).then(() => {
      reload();
      createMessage.success(t('common.undoSuccessText'));
    });
  };

  // 删除
  const handleDelete = async (record: Recordable) => {
    // isshortcut 为0 不关联 为1 关联
    record.isshortcut === '0'
      ? await deleteFile(record.id)
      : await DeleteFolderShortCut(selectedDocKey.value, record.id);
    reload();
    createMessage.success(t('common.delSuccessText'));
  };

  // 下载图档
  const handleDownload = throttle((record: Recordable) => {
    downloadFile(record.id, record.version, record.filename).then(() => {
      createMessage.success(t('common.downLoadSuccess'));
    });
  }, 3000);

  // 打印图档
  const handlePrint = (record: Recordable) => {
    printFile(record.oId, record.version).then((res) => {
      if (
        res.suffix == 'pdf' ||
        res.suffix == 'jpg' ||
        res.suffix == 'jpeg' ||
        res.suffix == 'png'
      ) {
        printJS({ printable: res.binaryStream, type: 'pdf', base64: true });
      } else {
        createMessage.error('暂不支持该格式打印');
      }
    });
  };

  //关联对象
  const handleAssociated = (record: Recordable) => {
    openAssociatedModal(true, {
      isAssociation: true,
      selectedDirKey: selectedDocKey.value,
      selectedDoctype: record.type,
      SelectedOid: record.oId,
      isFrom: '图档列表',
    });
  };

  // 反向关联零件
  const handleReverseAssociated = (record: Recordable) => {
    openSelectPartModal(true, { isFrom: '图文档工作区关联零件', record: record });
  };

  const assPartSuccess = (fromRecord, toRecord) => {
    // fromRecord:关联的零件 toRecord:被关联的零件
    const Association = ref<any>({
      folderid: selectedDocKey.value,
      oid: toRecord.oId,
      doctype: toRecord.type,
      selectedOid: fromRecord.oId,
      selectedDoctype: fromRecord.doctypeid,
    });
    addFolderBindingObject(Association.value).then((res) => {
      if (res) {
        reload();
        createMessage.success(t('routes.demo.documentManager.associatedSuccess'));
      }
    });
  };

  // 相关流程实例
  const handleFlowDetail = (record: Recordable) => {
    openFlowDetailModal(true, { currentRecord: record });
  };

  // 借阅功能
  const handleBorrow = async (record: Recordable) => {
    const isExit = await GetIsInWorkflow(record.oId);
    if (!isExit) {
      createMessage.error('该文件已在流程中，请先结束流程');
    } else {
      getBorrowBdDataJudge().then((res) => {
        if (res === '1') {
          if (record.state === '8') {
            const param = {
              record: record,
              currentDireId: selectedDocKey.value,
            };
            openBorrowModal(true, param);
          } else {
            createMessage.error(t('routes.demo.documentManager.onlyBorrowAble'));
          }
        } else {
          const param = {
            record: record,
            currentDireId: selectedDocKey.value,
          };
          openBorrowModal(true, param);
        }
      });
    }
  };

  // 废止
  const handleAbolish = async (record: Recordable) => {
    const isExit = await GetIsInWorkflow(record.oId);
    if (record.state !== '8') {
      createMessage.error('仅可废止生效的对象');
    } else if (!isExit) {
      createMessage.error('该文件已在流程中，请先结束流程');
    } else {
      JudgeAbolishedDocData(record.oId).then((res) => {
        if (res) {
          openModalCopy(true, {
            record: record,
            type: '废止流程',
            selectedFiles: '',
            projectid: '',
            projectName: '',
            taskName: '',
            formId: '',
            state: '图档',
            isUpdate: false,
          });
        }
      });
    }
  };

  // 新建流程
  const handleCreateFlow = async (record: Recordable) => {
    const isExit = await GetIsInWorkflow(record.oId);
    if (!isExit) {
      createMessage.error('该文件已在流程中，请先结束流程');
    } else {
      openModalCopy(true, {
        record: record,
        type: '通知流程',
        selectedFiles: '',
        projectid: '',
        projectName: '',
        taskName: '',
        formId: '',
        state: '图档',
        isUpdate: false,
      });
    }
  };

  // 工作指派
  const handleAssign = (record: Recordable) => {
    if (record.state !== '1') {
      createMessage.error(t('routes.demo.documentManager.objectNotCheckout'));
    } else {
      getWorkAssignList(record.id, '0').then((res) => {
        openDocWorkModal(true, { recordData: record, workAssignList: res, isFrom: '图档' });
      });
    }
  };

  // 递归查找所有父级节点
  const findParentKeys = (tree, targetKey, parentKeys = []) => {
    for (const node of tree) {
      if (node.key === targetKey) {
        return parentKeys;
      }
      if (node.children) {
        const result = findParentKeys(node.children, targetKey, [...parentKeys, node.key]);
        if (result.length) return result;
      }
    }
    return [];
  };

  // 复制代号
  const handleCopyFallback = (text) => {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed'; // 避免影响页面布局
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand('copy');
      createMessage.success(t('common.copySuccessText'));
    } catch (err) {
      createMessage.error('复制失败！');
    }
    document.body.removeChild(textarea);
  };

  const handleCopy = (name) => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(name)
        .then(() => {
          createMessage.success(t('common.copySuccessText'));
        })
        .catch(() => {
          handleCopyFallback(name);
        });
    } else {
      handleCopyFallback(name);
    }
  };

  // 提交
  async function handleSubmit() {
    if (isBdData.value.isBd === '0') {
      // 图档
      openDirModal(true, {
        fileType: fileType.value,
        selectedDirKey: selectedDocKey.value,
        isUpdate: false,
        record: null,
      });
    } else if (isBdData.value.isBd === '1') {
      // 表单
      openFormTypeModal(true, {
        fileType: fileType.value,
        selectedDirKey: selectedDocKey.value,
        type: '新增',
      });
    }
    cancelDocType();
  }
  const cancelDocType = () => {
    fileType.value = null;
    closeDireTypeModal();
  };

  const handleSelect = (value) => {
    isBdData.value = documentTypeList.value.find((item) => item.fileTypeId === value);
  };

  // 浏览功能
  const handleBrowse = async (record: Recordable) => {
    await handleBrowseFile(record, '图文档工作区');
  };
  // 版本浏览功能
  const versionPreview = throttle((record: Recordable) => {
    GetPreviewSettings().then((res) => {
      if (res[0].resourceName == 'kkFile') {
        // kkFile
        browseFile(versionOid.value, record.版本).then((res) => {
          let url = res[0]; //要预览文件的访问地址
          window.open(res[1] + ':8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)));
        });
      } else if (res[0].resourceName == 'autoVue') {
        // autoView
        ExtractFileByAutoView(versionOid.value, record.版本).then((res) => {
          let url = res[0]; //要预览文件的访问地址
          window.open(
            res[1] +
              ':5098/AutoVue/OpenApplet.html?browse=' +
              encodeURIComponent(Base64.encode(url)),
          );
        });
      }
    });
  }, 3000);

  // 比较浏览
  const handleCompareBrowse = (record: Recordable) => {
    openCompareModal(true, { record });
  };

  // 版本比较
  const handleVersionCompare = (record: Recordable) => {
    openVersionModal(true, { record });
  };

  // 使用情况
  const handleUsage = (record: Recordable) => {
    openUsageModal(true, { record });
  };

  // 当选中的行发生改变时调用
  const onSelectChange = (selectedRowKeys: (string | number)[], selectedRowsData: any) => {
    checkedKeys.value = selectedRowKeys; // 更新选中的键
    selectedRows.value = selectedRowsData; // 更新选中的行数据
  };

  const onSelectVerChange = (selectedRowKeys: (string | number)[], selectedRowsData: any) => {
    checkedVerKeys.value = selectedRowKeys; // 更新选中的键
    selectedVerRows.value = selectedRowsData; // 更新选中的行数据
  };

  // 比较浏览
  const CompareBrowse = () => {
    if (checkedVerKeys.value.length > 2 || checkedVerKeys.value.length < 2) {
      createMessage.error('只能选择两个文件进行对比浏览');
    } else {
      const arr: any[] = [
        {
          oid: versionOid.value,
          ver: selectedVerRows.value[0].版本,
          type: 0,
        },
        {
          oid: versionOid.value,
          ver: selectedVerRows.value[1].版本,
          type: 0,
        },
      ];

      ExtractManyFileByAutoView(arr)
        .then((res) => {
          if (!res || res.length < 2) {
            return;
          }

          const [{ viewUrl: url1, serverUrl, doctype }, { viewUrl: url2 }] = res;
          const is3D = doctype === '3D图纸';
          const compareType = is3D ? 'compare3D' : 'compare2D';

          const encodedFile1 = encodeURIComponent(Base64.encode(url1));
          const encodedFile2 = encodeURIComponent(Base64.encode(url2));
          const viewerUrl = `${serverUrl}:5098/AutoVue/OpenApplet.html?${compareType}=true&file1=${encodedFile1}&file2=${encodedFile2}`;
          window.open(viewerUrl);
          // 清空选中
          checkedVerKeys.value = [];
          selectedVerRows.value = [];
        })
        .catch((err) => {
          console.error('预览文件对比失败', err);
        });
    }
  };

  const getBatchData = () => {
    openBatchModal(true, { dataSource: selectedRows.value });
  };

  // 计算零件信息
  const partInfoTitle = (partInfo) => {
    if (!partInfo) {
      return '暂无零件信息';
    }
    const { partThitObjectId, partName, partType, partStatus, partVersion } = partInfo;
    // 假设你在全局过滤器里定义了 filterDocumentStatus
    const filterState = proxy.$filters.filterPartStatus(partStatus);
    // 多行显示，每行一个字段
    return [
      `零件代号：${partThitObjectId}`,
      `零件名称：${partName}`,
      `零件类型：${partType}`,
      `零件状态：${filterState}`,
      `零件版本：${partVersion}`,
    ].join('\n');
  };

  // 表格初始化
  const [registerTable, { reload }] = useTable({
    titleHelpMessage: 'docManagerIndex',
    columns: getDocumentColumns(),
    api: getPrdFileList,
    bordered: true,
    useSearchForm: true,
    formConfig: getDocumentConfig(), // 表单配置
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    // pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    pagination: false,
    scroll: { y: 220 },
    striped: true,
    customRow: (record: Recordable) => {
      return {
        onClick: () => {
          selectRowClass.value = record.id;
          fileName.value = record.name;
          version.value = record.version;
          type.value = record.type;
          createTime.value = record.creattime;
        },
      };
    },
    rowClassName: (record: Recordable) => {
      return record.id === selectRowClass.value ? 'table-row-selected' : '';
    },
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 版本展示
  const [registerVersion, { setColumns: setVersionColumns }] = useTable({
    titleHelpMessage: 'docManagerVersion',
    columns: getPartVersionList(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: false }, // 表格设置工具配置
    canResize: false,
    actionColumn: {
      width: 100,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  // 相关图档
  const [registerAssociatedImage] = useTable({
    titleHelpMessage: 'docManagerAssociated',
    columns: getAssociatedImageList(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: false }, // 表格设置工具配置
    canResize: false,
  });

  // 查看下列
  const getCurrentRecord = (record) => {
    versionOid.value = record.oId;
    SelectPrdForFiles(record.oId).then((res) => {
      let newId = [res[0].folderUrl];
      selectedKeys.value = newId;
      const parents = findParentKeys(documentData.value, res[0].folderUrl); // 查找所有父节点
      expandedKeys.value = [...new Set([...expandedKeys.value, ...parents])]; // 确保去重
    });
    const isShowVersion = record.prdpower?.some((item) => item.permissionNames == '版本展示');
    if (isShowVersion) {
      getPrdFileVersionList(record.id).then((res) => {
        nextTick(() => {
          if (res !== null) {
            versionList.value = res.map((item) => ({
              ...item,
              创建日期: dayjs(item.创建日期).format('YYYY-MM-DD'),
            }));
            let newArr = [];
            for (let i = 0; i < Object.keys(versionList.value[0]).length; i++) {
              let obj = {
                title: '',
                dataIndex: '',
                fixed: i == 0 ? 'left' : '',
                width: i == 0 ? 300 : 120,
              };
              obj.title = Object.keys(versionList.value[0])[i];
              obj.dataIndex = Object.keys(versionList.value[0])[i];
              newArr.push(obj);
            }
            setVersionColumns(newArr);
          }
        });
      });
    } else {
      createMessage.error('您没有权限查看版本信息');
    }
    // 相关图档列表
    getRelatedFileList(record.id).then((res) => {
      associatedImageList.value = res;
    });
    // 图档浏览
    // browseFile(record.id, record.version).then((res) => {
    //   let url =
    //     'http://127.0.0.1:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(res[0]));
    //   previewSrc.value = url;
    //   description.value = t('common.loadingText');
    // });
  };

  // 弹窗
  const [registerDireModal, { openModal: openDireModal }] = useModal();

  // 发起流程弹窗
  const [registerModalCopy, { openModal: openModalCopy }] = useModal();

  // 对象类绑定设置弹窗
  const [registerObjBindModal, { openModal: openObjBindModal }] = useModal();

  // 关联，反关联弹窗
  const [registerAssociatedModal, { openModal: openAssociatedModal }] = useModal();

  // 相关流程实例
  const [registerFlowDetailModal, { openModal: openFlowDetailModal }] = useModal();

  // 文件导入弹窗
  const [registerFileImportModal, { openModal: openFileImportModal }] = useModal();

  // 借阅流程弹窗
  const [registerBorrowModal, { openModal: openBorrowModal }] = useModal();

  // 目录工作指派
  const [registerDireWorkModal, { openModal: openDireWorkModal }] = useModal();

  // 文档工作指派
  const [registerDocWorkModal, { openModal: openDocWorkModal }] = useModal();

  // 新建图档-图档类型
  const [registerDireTypeModal, { openModal: openDireTypeModal, closeModal: closeDireTypeModal }] =
    useModal();

  // 新建图档-图档弹窗
  const [registerDocumentTypeModal, { openModal: openDirModal }] = useModal();

  // 使用情况
  const [registerUsageModal, { openModal: openUsageModal }] = useModal();

  //提取导入
  const [registerExtractImportModal, { openModal: openExtractImportModal }] = useModal();

  // Excel导入
  const [registerExcelImportModal, { openModal: openExcelImportModal }] = useModal();

  // 新建流程
  const [registerCreateFlowModal, { openModal: openNewFlowModal }] = useModal();

  // 目录权限设置
  const [registerPermissionModal, { openModal: openDirePermissionModal }] = useModal();

  // 表单类型新建图文档
  const [registerFormTypeModal, { openModal: openFormTypeModal }] = useModal();

  // 发布文档
  const [registerRelModal, { openModal: openRelModal }] = useModal();

  // 版本比较
  const [registerDocVersionModal, { openModal: openVersionModal }] = useModal();

  // 比较浏览
  const [registerCompareViewModal, { openModal: openCompareModal }] = useModal();

  // 解绑目录
  const [registerUnbindModal, { openModal: openUnbindModal }] = useModal();

  // 批量操作
  const [registerBatchModal, { openModal: openBatchModal }] = useModal();

  const [registerOnlyOfficeModal, { openModal: openPreviewModal }] = useModal();

  // 关联零件
  const [registerPartManagerModal, { openModal: openSelectPartModal }] = useModal();
</script>

<style lang="less" scoped>
  .documentManager {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30px;
    height: 80px;
    border: 1px solid #aaa;
    writing-mode: vertical-lr;
    cursor: pointer;
  }

  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  ::v-deep(.table-row-selected) {
    background-color: #e6f7ff !important;
  }

  .text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .tree-container {
    height: 80vh;
    overflow-y: auto;
  }
</style>
